﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection.Emit;

namespace config2
{
    internal class Program
    {
        //推荐使用选项方式读取，和DI结合更好，且更好利用“reloadonchange”机制。
        static void Main(string[] args)
        {
            ServiceCollection service = new ServiceCollection();
            service.AddScoped<TestController>();
            service.AddScoped<Test2Controller>();

            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            //json文件配置
            //configurationBuilder.AddJsonFile("config.json", optional: true, reloadOnChange: true);
            //命令行配置
            //database=test password=123456 ids:0=4 ids:1=5 log:type=logtest log:level=info log:ids:0=4 log:ids:1=5
            //configurationBuilder.AddCommandLine(args);
            //环境变量
            //database=test password=123456 ids:0=4 ids:1=5 log:type=logtest log:level=info log:ids:0=4 log:ids:1=5
            //无前缀 有前缀c_database=test
            configurationBuilder.AddEnvironmentVariables();
            IConfigurationRoot config = configurationBuilder.Build();
            //!!!把这个节点绑定到这个对象
            service.AddOptions()
                .Configure<Config>(e => config.Bind(e))
                .Configure<Log>(e => config.GetSection("log").Bind(e));

            using (var sp = service.BuildServiceProvider())
            {
                //配置文件改变，获取的值不改变
                var t = sp.GetRequiredService<TestController>();
                t.test();

                var t1 = sp.GetRequiredService<Test2Controller>();
                t1.test();

                //配置文件改变，获取的值也改变
                //while (true)
                //{
                //    using (var sc = sp.CreateScope())
                //    {
                //        var t2 = sp.GetRequiredService<TestController>();
                //        t.test();

                //        var t3 = sp.GetRequiredService<Test2Controller>();
                //        t1.test();
                //    }
                //    Console.WriteLine();
                //    Console.ReadKey();
                //}
            }
            Console.ReadKey();
        }


    }
}